<?php

namespace app\api\controller;

use app\api\model\UserModel;

class User extends \app\BaseController
{
    public function register()
    {
        $date = input('post.');
        //验证数据
        $validate = new \app\api\validate\UserValidate();
        $result = $validate->scene('add')->check($date);
        if (!$result) {
            return error($validate->getError());
        }
        $user = UserModel::where('mobile',$date['mobile'])->find();
        if($user){
            return error('重复使用该手机号注册');
        }
        if($date['account_type'] == 1){
            $r = checkSmsCode($date['mobile'],$date['code']);
            if(!$r){
                return error('验证码验证失败');
            }
        }
        $randStr = createRandStr();
        $password = md5($date['password'].$randStr);
        $date['password'] = $password;
        $date['salt'] = $randStr;
        if (UserModel::create($date)){
            return success('注册成功');
        }else{
            return error('注册失败');
        }
    }

    public function login()
    {
        $date = input('post.');
        //验证数据
        $validate = new \app\api\validate\UserValidate();
        $result = $validate->scene('login')->check($date);
        if (!$result) {
            return error($validate->getError());
        }
        $user = UserModel::where('mobile',$date['mobile'])->find();
        if(!$user){
            return error('该手机号未注册');
        }
        if(md5($date['password'].$user['salt']) != $user['password']){
            return  error('密码错误');
        }
        return success('登录成功',[
           'token' => singToken($user['id'],$user['mobile'])
        ]);
    }

    public function Sms(){
        $mobile = input('mobile');
        $yzm = sendAliSms($mobile);
        if($yzm == true){
            return success('验证码发送成功');
        }else{
            return error('验证码发送失败');
        }
    }
}